import SmartModal from "@/components/smartmodal";
import EditPwd from "./components/EditComp";
import { resetPwdApi } from "./service";
import { extractToken, refactorToken } from "@/utils/login";
import request from "@/utils/request";
import {
  generateUuid,
  getChromeVersion,
  isIE,
  URI_NAME,
  getGantPopupContainer,
  getSearchParams,
} from "@/utils/utils";
import { Alert, Col, Dropdown, Icon, Menu, Row } from "antd";
import classnames from "classnames";
import { Header } from "gantd";
import React, { useEffect, useRef, useState } from "react";
import { connect, getLocale, history, Link, setLocale } from "umi";
import LoginComponents from "./components/Login";
import ValidateCode from "./components/Login/ValidateCode";
import styles from "./style.less";
const { UserName, Password, Submit } = LoginComponents;

const Login = (props: any) => {
  const { login, submitting, settings, config } = props;
  const { LOGIN_CONFIG, BASE_CONFIG } = settings;

  const {
    COMMON_CONFIG: {
      showDownloadClientLink,
      downloadClientUrl,
      showChangeLanguageMenu,
      validateCode,
      showAgentSuggest,
      agentIncompatiblePreventLogin,
    },
  } = config;
  const { status = "", type: loginType } = login;

  const {
    loginAlign = "center",
    loginFormStyle,
    loginFormTextColor = "#000",
    backgroundBlur = "0px",
    customHeader,
    customFooter,
    backgroundImage = "",
    backgroundColor = "#fff",
    langulageIconColor = "rgba(0,0,0,0.65)",
    loginFormShowLogo = false,
    loginFormShowName = true,
    copyrightAlign = "left",
    headerTheme = "dark",
  } = LOGIN_CONFIG;

  const {
    logoImage,
    logoImageWhite,
    logoName,
    appTitle,
    logoNameEn,
    appTitleEn,
    copyright,
  } = BASE_CONFIG;

  const isIEBoswer: any = isIE();
  const chromeVersion = getChromeVersion();
  const clientWidth = window.innerWidth;
  let canLogin = true;
  if (agentIncompatiblePreventLogin) {
    canLogin =
      isIEBoswer || isIEBoswer == 11 || (chromeVersion && chromeVersion < 66)
        ? false
        : true;
  }

  const [validateCodekey, setValidateCodekey] = useState("1");
  const [editPwdVisible, setEditPwdVisible] = useState(false);
  const [tokenValue, setTokenValue] = useState("");

  const loginFormRef = useRef();

  useEffect(() => {
    (async () => {
      await props.dispatch({
        type: "settings/getSetting",
      });
    })();
  }, []);

  useEffect(() => {
    document.title =
      "登录" + "-" + window["documentTitle"] ? window["documentTitle"] : "";
  }, []);

  //登录成功的回调
  const loginSuccessCallback = async () => {
    const res = await request(
      "/security/checkPasswordUpdateTime",
      {
        method: "POST",
        data: {},
      },
      {
        showError: false,
      }
    );
    if (res !== "pass") {
      // 临时清除token，待修改完密码后恢复
      var tokenValue = await extractToken();
      setTokenValue(tokenValue);
      setEditPwdVisible(true);
    } else {
      // 这里获取原url
      let targetUrl = localStorage.getItem("targetUrl");
      targetUrl = targetUrl=="/?forceLocal=true"?"/":(targetUrl || "/");
      history.push(targetUrl);
      localStorage.removeItem("targetUrl");
    }
  };

  //修改密码成功的回调
  const editPasswordCallback = async () => {
    //恢复token
    await refactorToken(tokenValue);
    history.push("/");
  };

  //点击登录
  const handleSubmit = (err: any, values: FromDataType) => {
    const { validate, ...restValue } = values;
    const { config } = props;
    const {
      COMMON_CONFIG: { validateCode },
    } = config;
    const { setFields } = loginFormRef.current;
    if (!err) {
      const { dispatch } = props;
      if (validateCode) {
        if (!validate.code)
          return setFields({
            validate: {
              value: values.validate,
              errors: [new Error("请输入验证码")],
            },
          });
        dispatch({
          type: "login/login",
          payload: {
            validateCode: validate.code,
            validateCodeId: validate.id,
            loginSuccessCallback,
            errorCallback: () => {
              setValidateCodekey(generateUuid());
            },
            ...restValue,
          },
        });
      } else {
        dispatch({
          type: "login/login",
          payload: {
            loginSuccessCallback,
            ...restValue,
          },
        });
      }
    }
  };

  //提示信息
  const renderMessage = (content: string) => (
    <Alert
      style={{ marginBottom: 24 }}
      message={content}
      type="error"
      showIcon
    />
  );

  //切换语言
  const onMenuClick = (item: any) => {
    const { key } = item;
    switch (key) {
      case "zh":
        setLocale("zh-CN");
        break;
      case "en":
        setLocale("en-US");
        break;
      default:
        break;
    }
  };

  //切换语言菜单
  const menu = (
    <Menu onClick={onMenuClick}>
      <Menu.Item key="zh">简体中文</Menu.Item>
      <Menu.Item key="en">English</Menu.Item>
    </Menu>
  );

  return (
    <div className={classnames("gant-layout", styles.loginPage)}>
      <div
        className={styles.bkg}
        style={{
          backgroundColor: `${backgroundColor}`,
          backgroundImage: `url(${backgroundImage})`,
          filter: `blur(${backgroundBlur})`,
        }}
      ></div>
      <Row className="full">
        {loginAlign == "right" && <Col span={12} className="uiui"></Col>}
        <Col
          span={loginAlign == "center" ? 24 : 12}
          className="aligncenter"
          style={{ height: "100%" }}
        >
          <div className={styles.main} style={{ ...loginFormStyle }}>
            <LoginComponents
              // defaultActiveKey={type}
              // onTabChange={this.onTabChange}
              onSubmit={handleSubmit}
              ref={(form: any) => {
                loginFormRef.current = form;
              }}
            >
              <div
                style={{
                  display: "flex",
                  justifyContent: "center",
                  flexDirection: "column",
                }}
              >
                {loginFormShowLogo && (
                  <img
                    src={logoImage}
                    style={{ width: 100, height: 100, margin: "0 auto" }}
                  />
                )}
                {loginFormShowName && (
                  <div style={{ fontSize: "42px", color: loginFormTextColor }}>
                    <b className="login-app-name">
                      {getLocale() == "zh-CN" && appTitle}
                      {getLocale() == "en-US" && appTitleEn}
                    </b>
                  </div>
                )}
              </div>
              {canLogin && (
                <>
                  <Header
                    title={"登录"}
                    bottomLine={false}
                    color={loginFormTextColor}
                  />
                  {status === "error" &&
                    loginType === "account" &&
                    !submitting &&
                    renderMessage("错误")}
                  <UserName
                    name="userName"
                    placeholder={"用户名"}
                    rules={[
                      {
                        required: true,
                        message: "请输入用户名",
                      },
                    ]}
                    className="marginv10"
                  />
                  <Password
                    name="password"
                    placeholder={"密码"}
                    rules={[
                      {
                        required: true,
                        message: "请输入密码",
                      },
                    ]}
                    // onPressEnter={() =>
                    //   loginFormRef.current && loginFormRef.current.validateFields(handleSubmit)
                    // }
                    className="marginv10"
                  />
                  {validateCode && (
                    <ValidateCode
                      key={validateCodekey}
                      name="validate"
                      placeholder={"验证码"}
                      size="large"
                      className="marginv10"
                    />
                  )}
                  <Submit loading={submitting} className="marginv10">
                    {"登录"}
                  </Submit>
                </>
              )}
              {showAgentSuggest && clientWidth < 1366 && (
                <Alert
                  message="警告"
                  description={
                    <>
                      {"当前浏览器宽度为"}
                      {clientWidth},{"本软件最优宽度最小为"}: 1680,
                      {"建议放大浏览器或更换至大屏幕"}
                    </>
                  }
                  type="warning"
                  showIcon
                  closable
                />
              )}
              {showAgentSuggest && (isIEBoswer || isIEBoswer == 11) && (
                <Alert
                  message="警告"
                  description={
                    <>
                      {"当前浏览器为IE浏览器"},{"某些高级功能不支持"},
                      {"请使用谷歌或火狐等现代浏览器"},
                      {"或下载客户端使用"}
                    </>
                  }
                  type="warning"
                  showIcon
                  closable
                />
              )}
              {showAgentSuggest && chromeVersion && chromeVersion < 66 && (
                <Alert
                  message="警告"
                  description={
                    <>
                      {"当前谷歌浏览器版本过低"},{"某些高级功能不支持"},
                      {"请使用谷歌浏览器"}
                      v66
                      {"及以上版本"}
                    </>
                  }
                  type="warning"
                  showIcon
                  closable
                />
              )}
              {/* <div className={styles.other}>
              <FormattedMessage id="login.login.sign-in-with" />
              <Icon type="alipay-circle" className={styles.icon} theme="outlined" />
              <Icon type="taobao-circle" className={styles.icon} theme="outlined" />
              <Icon type="weibo-circle" className={styles.icon} theme="outlined" />
              <Link className={styles.register} to="/user/register">
                <FormattedMessage id="login.login.signup" />
              </Link>
            </div> */}
            </LoginComponents>
          </div>
        </Col>
        {loginAlign == "left" && <Col span={12} className="uiui"></Col>}
      </Row>
      {customHeader ? (
        <div
          style={{ width: "100%", position: "absolute", top: 0, left: 0 }}
          dangerouslySetInnerHTML={{ __html: customHeader }}
        ></div>
      ) : (
        <div
          style={{
            width: "100%",
            position: "absolute",
            top: 0,
            left: 0,
            padding: "10px",
          }}
        >
          <img
            src={headerTheme == "light" ? logoImageWhite : logoImage}
            style={{
              height: "40px",
              width: "auto",
              display: "inline-block",
              verticalAlign: "bottom",
            }}
          />
          <div
            style={{
              fontSize: "24px",
              fontWeight: "bold",
              lineHeight: "40px",
              display: "inline-block",
              marginLeft: "10px",
              color: headerTheme == "light" ? "#fff" : "#000",
            }}
          >
            {getLocale() == "zh-CN" && logoName}
            {getLocale() == "en-US" && logoNameEn}
          </div>
        </div>
      )}
      {customFooter ? (
        <div
          style={{ width: "100%", position: "absolute", bottom: 0, left: 0 }}
          dangerouslySetInnerHTML={{ __html: customFooter }}
        ></div>
      ) : (
        <div
          style={{
            width: "100%",
            position: "absolute",
            bottom: 0,
            left: 0,
            padding: "10px",
          }}
        >
          <div
            style={{
              width: "100%",
              lineHeight: "30px",
              fontSize: "14px",
              color: "#696969",
              textAlign: copyrightAlign,
            }}
          >
            {(
              <p
              style={{
                // textAlign: copyrightAlign == 'left' ? 'right' : (copyrightAlign == 'center' && 'center')
                margin: 0,
              }}
            >
              {"为了更好地体验，推荐使用Chrome（谷歌）浏览器"}
            </p>
            )}
            <p
              style={{
                // textAlign: copyrightAlign
                margin: 0,
              }}
            >
              {copyright.replace("{now}", new Date().getFullYear())}
            </p>
          </div>
        </div>
      )}
      {showChangeLanguageMenu && (
        <Dropdown overlay={menu} getPopupContainer={getGantPopupContainer}>
          <Icon
            type="global"
            className={styles.global}
            style={{ color: langulageIconColor ? langulageIconColor : "" }}
          />
        </Dropdown>
      )}
      <SmartModal
        itemState={{ height: 260 }}
        title={"密码已过期" + "," + "请修改密码"}
        visible={editPwdVisible}
        footer={null}
      >
        <EditPwd
          showBottomBtn
          successCallback={editPasswordCallback}
          resetPwdApi={resetPwdApi}
          accountSettingsEditPwd={{}}
        />
      </SmartModal>
    </div>
  );
};

export default connect(
  ({
    login,
    loading,
    settings,
    config,
  }: {
    login: any;
    settings: any;
    loading: {
      effects: {
        [key: string]: string;
      };
    };
    config: any;
  }) => ({
    login,
    settings,
    config,
    submitting: loading.effects["login/login"],
  })
)(Login);
